package com.wip.reportingservice.daos.impls;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.wip.reportingservice.daos.entities.ClientsTable;
import com.wip.reportingservice.daos.interfaces.IClientsDao;

@Repository
@Transactional
public class ClientsDaoImpl implements IClientsDao {

	private static final Logger logger = LoggerFactory
			.getLogger(PagesDaoImpl.class);

	@Autowired
	private SessionFactory sessionFactory;

	public void save(ClientsTable client) {
		logger.info("ClientsDaoImpl.save");
		sessionFactory.getCurrentSession().save(client);
	}

	public void update(ClientsTable client) {
		sessionFactory.getCurrentSession().update(client);
	}

	public void delete(ClientsTable client) {
		sessionFactory.getCurrentSession().delete(client);
	}

	public ClientsTable getById(int id) {

		final Criteria crit = sessionFactory.getCurrentSession()
				.createCriteria(ClientsTable.class);

		crit.add(Restrictions.idEq(id));

		return (ClientsTable) crit.list().get(0);
	}

	@Override
	public String test() {
		return "clientdao";
	}

	@Override
	public ClientsTable getByName(String name) {
		logger.info("ClientsDaoImpl.getByName");

		final Criteria crit = sessionFactory.getCurrentSession()
				.createCriteria(ClientsTable.class);

		crit.add(Restrictions.ilike("clientName", name));

		return (ClientsTable) crit.list().get(0);
	}

	@Override
	public  List<ClientsTable> getAll() {
		final Criteria crit = sessionFactory.getCurrentSession().createCriteria(ClientsTable.class)
			    .setProjection(Projections.projectionList()
			      .add(Projections.property("clientName"), "clientName"))
			    .setResultTransformer(Transformers.aliasToBean(ClientsTable.class));

			  List<ClientsTable> list = crit.list();
			  
			  return list;
	}

}
